package com.gaoyuzhe.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 自定义的轮训的负载实现
 * @author gaoyuzhe
 */
@Component
public class MyRoundLb implements LoadBalancer {

    private AtomicInteger atomicInteger =new AtomicInteger(0);

    public final int getIncrease(){
        for(;;){
            int current = atomicInteger.get();
            int next = current >=Integer.MAX_VALUE ? 0:current+1;
            if(atomicInteger.compareAndSet(current,next)){
                System.out.print("当前请求次数" + next);
                return next;
            }
        }
    }

    @Override
    public ServiceInstance getLoadBalanceInstance(List<ServiceInstance> instanceList) {
        int index = getIncrease() % instanceList.size();
        return instanceList.get(index);
    }
}
